/**
 * 实现一个LazyMan，可以按照以下方式调用:
    LazyMan(“Hank”)输出:
    Hi! This is Hank!

    LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
    Hi! This is Hank!
    //等待10秒..
    Wake up after 10
    Eat dinner~

    LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
    Hi This is Hank!
    Eat dinner~
    Eat supper~

    LazyMan(“Hank”).eat(“supper”).sleepFirst(5)输出
    //等待5秒
    Wake up after 5
    Hi This is Hank!
    Eat supper
 */

class _LazyMan {
  constructor(name) {
    this.callbacks = []
    const task = () => {
      this.say(name)
    }
    this.callbacks.push(task)
    setTimeout(async () => {
      for (let i = 0; i < this.callbacks.length; i++) {
        const fn = this.callbacks[i]
        await fn()
      }
    })
  }
  say (name) {
    console.log(` Hi This is ${name}!`)
    return this
  }
  eat (food) {
    const task = () => {
      console.log(`Eat ${food}~`)
    }
    this.callbacks.push(task)
    return this
  }
  // 阻塞time * 1000秒后在执行下面的任务
  sleep (time) {
    const task = () => {
      return new Promise((resolve) => {
        setTimeout(resolve, time * 1000)
      })
        .then(() => {
          console.log(`Wake up after ${time}`)
        })
    }
    this.callbacks.push(task)
    return this
  }
  // 先阻塞time * 1000秒后在依次执行任务
  sleepFirst (time) {
    const task = () => {
      return new Promise((resolve) => {
        setTimeout(resolve, time * 1000)
      })
        .then(() => {
          console.log(`Wake up after ${time}`)
        })
    }
    this.callbacks.unshift(task)
    return this
  }
}
function LazyMan (name) {
  return new _LazyMan(name)
}

// LazyMan('Hank')
// LazyMan('Hank').sleep(10).eat('dinner')
// LazyMan('Hank').eat('dinner').eat('supper')
LazyMan('Hank').eat('supper').sleepFirst(5)

// function p1 () {
//   return new Promise((resolve) => {
//     setTimeout(() => {
//       console.log('p1')
//       resolve()
//     }, 3000)
//   })
// }
// function p2 () {
//   console.log('p2')
// }
// function p3 () {
//   console.log('p3')
// }
// const arr = [p2, p1, p3];

// 为什么不会阻塞？
// arr.forEach(async fn => {
//   await fn()
// });

// (async function () {
//   for (let i = 0; i < arr.length; i++) {
//     const fn = arr[i];
//     await fn()
//   }
// })()



